package cpu.footprint.ui;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.MyApplication;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.view.XListView;

/**
 * Created by Administrator on 2017/10/17.
 */
@ContentView(R.layout.activity_active_record)
public class ActiveRecordActivity extends BaseActivity implements XListView.IXListViewListener {
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    @ViewInject(R.id.listView)
    private XListView listView;
    private CommonAdapter<User> adapter;//群组适配器
    private Context context;
    private List<User> userList = new ArrayList<>();
    private int startCount = 1;//页码
    private int activeId=0;
    private int pagerCount = 8;// 每页显示多少条数据
    private boolean isHasMore = true;
    private MyApplication myApp;
    private User user;
    private Date reshDate = null;
    private Dialog mDialog;
    private int flag = 0;//(0:初始 无刷新无加载，1刷新 2加载更多)
    private SimpleDateFormat reshSdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context=ActiveRecordActivity.this;
        myApp = (MyApplication) getApplication();
        user = myApp.getUser();
        activeId = getIntent().getIntExtra("activeId",0);
        initView();
        requestData();
    }

    private void initView() {
        title_content.setText("参与用户");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.GONE);
        mDialog = showLoadingDialog(this);
        initAdapter();
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                User active = userList.get(position - 1);
//                Intent intent = new Intent(ActiveRecordActivity.this, ActiveDetailActivty.class);
//                intent.putExtra("active", active);
//                intent.putExtra("joined", true);
//                startActivityForResult(intent, 2);
//                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<User>(context, userList, R.layout.active_record_item) {
            @Override
            public void convert(ViewHolder helper, User item,
                                int position) {
                helper.setText(R.id.text_nickName,item.getNickName());
                helper.setText(R.id.text_phone,item.getMobilePhone());
                ImageView imageView = helper.getView(R.id.image_HeadPic);
                Picasso.with(context).load(ApiUrl.URL_HOST + item.getHeadPicture()).placeholder(R.mipmap.head).into(imageView);
            }
        };
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void requestData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("from", startCount + "");
        map.put("pagerCount", pagerCount + "");
        map.put("activeId", activeId+"");
        map.put("mobilePhone", user.getMobilePhone());
        map.put("token", user.getToken());
        APIService.Post(ApiUrl.URL_GET_ACTIVERECORD, map, new RespCallBack<BaseBean<User>>(ActiveRecordActivity.this) {
            @Override
            public void onSuccess(BaseBean<User> result) {
                super.onSuccess(result);
                if (result.success) {
                    if (result.datas.size() < pagerCount) {
                        isHasMore = false;
                    } else {
                        isHasMore = true;
                    }
                    if (flag == 1 || flag == 0) {
                        userList.clear();
                    } else if (flag == 2) {
                        listView.setSelection(startCount - pagerCount);
                    }
                    userList.addAll(result.datas);
                    initAdapter();
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                onLoad();
                if (mDialog != null && mDialog.isShowing())
                    mDialog.dismiss();
            }
        });
    }


    @Event(value = {R.id.title_back})
    private void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                ActiveRecordActivity.this.finish();
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            default:
                break;
        }
    }

    /**
     * 停止刷新
     */
    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        reshDate = new Date();
        listView.setRefreshTime(reshSdf.format(reshDate));
    }

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh() {
        flag = 1;
        startCount = 1;
        requestData();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (isHasMore) {
            startCount++;
            flag = 2;
            requestData();
        } else {
            listView.setSelection(userList.size() - 1);
            listView.pauseLoadMore();//已经到底啦
        }
    }
}
